/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.amuthu.parser;

import java.util.logging.Level;
import java.util.logging.Logger;
import org.amuthu.DataStore;
import org.amuthu.expression.Expression;
import org.amuthu.expression.binary.ArithmeticExpression;
import org.amuthu.expression.binary.ComparisionExpression;
import org.amuthu.expression.binary.LogicExpression;
import org.amuthu.expression.exception.InvalidArgumentException;
import org.amuthu.expression.function.FunctionEvaluator;
import org.amuthu.expression.function.FunctionExpression;
import org.amuthu.expression.function.FunctionManager;
import org.amuthu.expression.terminal.NumberExpression;
import org.amuthu.expression.terminal.QuoteExpression;
import org.amuthu.expression.unary.UnaryExpression;

/**
 *
 * @author prabhu
 */
public class DayDependencyVisitor extends ExpressionVisitor
{
   private int nbDays;
   private DataStore dataStore;

   public DayDependencyVisitor(DataStore dataStore)
   {
      this.dataStore = dataStore;
   }

   @Override
   public double evaluate(Expression expr)
   {
      expr.accept(this);
      return (double) nbDays;
   }

   @Override
   public void visit(ComparisionExpression expr)
   {
      expr.getChild(0).accept(this);
      expr.getChild(1).accept(this);
   }

   @Override
   public void visit(LogicExpression expr)
   {
      expr.getChild(0).accept(this);
      expr.getChild(1).accept(this);
   }

   @Override
   public void visit(NumberExpression expr)
   {
      nbDays  = (int) expr.getValue();
   }

   @Override
   public void visit(ArithmeticExpression expr)
   {
      expr.getChild(0).accept(this);
      expr.getChild(1).accept(this);
   }

   @Override
   public void visit(QuoteExpression expr)
   {
   }

   @Override
   public void visit(UnaryExpression expr)
   {
      expr.getChild(0).accept(this);
   }

   @Override
   public void visit(FunctionExpression expr)
   {
      FunctionEvaluator evaluator = FunctionManager.getInst().getEvaluator(expr.getName());

      if (evaluator != null)
      {
         try
         {
            int days = evaluator.computeDayDependency(dataStore, expr.getChildren(), this);

            System.out.println(expr.getName() + " has " + days + " dependency");

            if (days > nbDays)
            {
               nbDays = days;
            }
         }
         catch (InvalidArgumentException ex)
         {
            Logger.getLogger(EvaluationVisitor.class.getName()).log(Level.SEVERE, null, ex);
         }
      }
   }

}
